<template>
  <el-row :gutter="20" class="custom-row">
    <!-- 左侧18列 -->
    <el-col :span="18">
      <!-- 这里放左侧表单内容 -->
      <el-card style="margin-bottom: 30px;">
        <template #header>
          <div class="card-header">
            <span>客户资料/{{ businessData?.name }}</span>
          </div>
        </template>
        <el-form :model="businessData" label-width="80px" style="margin-top: 20px;" label-position="top">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户姓名">
                <el-input v-model="businessData.name" :disabled="!isEditable" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号">
                <el-input v-model="businessData.phone" :disabled="!isEditable" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职业">
                <el-select v-model="businessData.occupation" placeholder="请选择" :disabled="!isEditable">
                  <el-option v-for="item in occupationOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="学历">
                <el-select v-model="businessData.education" placeholder="请选择" :disabled="!isEditable">
                  <el-option v-for="item in educationOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所在地区">
                <el-cascader
                  v-model="businessData.address"
                  :options="regionOptions"
                  placeholder="请选择地区"
                  :disabled="!isEditable"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微信号码">
                <el-input v-model="businessData.weixin" :disabled="!isEditable" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年龄">
                <el-input-number v-model="businessData.age" :min="0" :disabled="!isEditable" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="QQ">
                <el-input v-model="businessData.qq" :disabled="!isEditable" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别">
                <el-select v-model="businessData.gender" placeholder="未知" :disabled="!isEditable">
                  <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身高">
                <el-input-number v-model="businessData.height" :min="0" :disabled="!isEditable" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="体重">
                <el-input-number v-model="businessData.weight" :min="0" :disabled="!isEditable" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注">
                <el-input v-model="businessData.remark" :disabled="!isEditable" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card style="margin-bottom: 30px;">
        <template #header>
          <div class="card-header">
            <span>客户意向</span>
          </div>
        </template>
        <el-form :model="businessData" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="意向类型">
                <el-select v-model="businessData.intentionType" placeholder="课程分类">
                  <el-option v-for="item in intentionTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="意向课程">
                <el-select v-model="businessData.intentionCourse" placeholder="请选择">
                  <el-option v-for="item in courseOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="健身原因">
                <el-input v-model="businessData.reason" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="每周健身时间">
                <el-input-number v-model="businessData.hours" :min="0" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="意向金额">
                <el-input-number v-model="businessData.money" :min="0" style="width: 100%;" :precision="2" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="其他意向">
                <el-input v-model="businessData.othenIntention" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card style="margin-bottom: 30px;">
        <template #header>
          <div class="card-header">
            <span>沟通记录</span>
          </div>
        </template>
        <el-form :model="businessData" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="跟进状态">
                <el-select v-model="businessData.status" placeholder="请选择">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下次跟进时间">
                <el-date-picker
                  v-model="businessData.nextTime"
                  type="datetime"
                  placeholder="请选择日期时间"
                  style="width: 100%;"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="沟通重点">
                <el-select v-model="businessData.focus" placeholder="请选择">
                  <el-option v-for="item in focusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="沟通纪要">
                <el-input v-model="businessData.record2" type="textarea" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="24" style="text-align: right;">
              <el-button @click="goBack">返回</el-button>
              <el-button type="primary" @click="saveData">保存</el-button>
              <el-button type="success" @click="goBack">转为成交客户</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-col>
    <!-- 右侧6列 -->
    <el-col :span="6">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>商机跟进记录</span>
          </div>
        </template>
        <div v-if="followRecords.length">
          <div v-for="item in followRecords" :key="item.recordId" style="margin-bottom: 12px;">
            <div>
              <b><i>{{ item.createBy }}：</i></b>
              {{ item.info }}
            </div>
            <div style="color: #888; font-size: 13px;">
              {{ item.createTime.replace('T', ' ') }}
            </div>
          </div>
        </div>
        <div v-else style="color: #aaa;">暂无跟进记录</div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { computed } from 'vue'
import request from '../../../../utils/request'
import data from 'china-area-data/data'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const id = route.params.id

// 获取模式（view 或 follow）
const mode = computed(() => route.path.endsWith('/follow') ? 'follow' : 'view')

// 是否可编辑
const isEditable = computed(() => mode.value === 'follow')

// 定义数据变量
const businessData = ref({
  name: '',
  phone: '',
  job: '',
  education: '',
  address: [],
  wechat: '',
  age: null,
  qq: '',
  gender: '',
  height: null,
  weight: null,
  remark: '',
  province: '',
  city: '',
  area: '',
  intentionType: '',
  intentionCourse: '',
  info: '',
  reason: '',
  hours: null,
  money: null,
  othenIntention: '',
  status: '',
  nextTime: '',
  focus: '',
  record2: ''
})

// 定义教育选项
const educationOptions = ref([])
const genderOptions = ref([])
const occupationOptions = ref([])
const intentionTypeOptions = ref([])

function getOptions(parentCode = '86') {
  if (!data[parentCode]) return []
  return Object.entries(data[parentCode]).map(([code, name]) => {
    const children = getOptions(code)
    return {
      value: code,
      label: name,
      children: children.length ? children : undefined
    }
  })
}
const regionOptions = ref(getOptions())

const followRecords = ref([])

// 调用 API 获取数据
onMounted(async () => {
  try {
    const response = await request.get(`/tienchin/business/${id}`)
    businessData.value = response.data

    // 获取所有选项
    await Promise.all([
      getGender(),
      getEducation(),
      getOccupation(),
      getIntentionType(),
      getCourseOptions(),
      getStatusOptions(),
      getFocusOptions()
    ])

    // 处理性别数据
    const genderItem = genderOptions.value.find(opt => opt.value === businessData.value.gender)
    businessData.value.gender = genderItem ? genderItem.value : businessData.value.gender

    // 处理跟进状态数据
    const statusItem = statusOptions.value.find(opt => 
      opt.label === businessData.value.status || opt.value === businessData.value.status
    )
    if (statusItem) {
      businessData.value.status = statusItem.value
    }
    
    // 省市区中文转 code
    const provinceCode = findCodeByLabel('86', businessData.value.province)
    const cityCode = provinceCode ? findCodeByLabel(provinceCode, businessData.value.city) : null
    const areaCode = cityCode ? findCodeByLabel(cityCode, businessData.value.area) : null

    // 赋值给 el-cascader
    businessData.value.address = [provinceCode, cityCode, areaCode].filter(Boolean)

    await getFollowRecords()
  } catch (error) {
    console.error('获取数据失败:', error)
  }
})

// 获取初始数据
const getEducation = () => {
  request('system/dict/data/type/business_education').then((res: any) => {
    console.log(res)
    educationOptions.value = res.data.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))
  }).catch((error) => {
    console.error('获取教育数据失败:', error)
  })
}

// 获取性别选项
const getGender = async () => {
  try {
    const res = await request('system/dict/data/type/sys_user_sex')
    genderOptions.value = res.data.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))
  } catch (error) {
    console.error('获取性别数据失败:', error)
  }
}

// 获取职业选项
const getOccupation = async () => {
  try {
    const res = await request('system/dict/data/type/business_occupation')
    console.log('API 返回的职业数据:', res) // 调试信息
    occupationOptions.value = res.data.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))
  } catch (error) {
    console.error('获取职业数据失败:', error)
  }
}

function findCodeByLabel(parentCode, label) {
  const obj = data[parentCode]
  if (!obj) return null
  for (const [code, name] of Object.entries(obj)) {
    if (name === label) return code
  }
  return null
}

const getFollowRecords = async () => {
  try {
    const res = await request.get(`/tienchin/follow/record/business/${id}`)
    followRecords.value = res.data || []
  } catch (error) {
    console.error('获取跟进记录失败:', error)
  }
}

const getIntentionType = async () => {
  try {
    const res = await request('system/dict/data/type/course_type')
    intentionTypeOptions.value = res.data.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))
  } catch (error) {
    console.error('获取意向类型失败:', error)
  }
}

const courseOptions = ref([])

watch(
  () => businessData.value.intentionType,
  async (newType) => {
    if (newType) {
      try {
        const res = await request.get(`/tienchin/business/course/${newType}`)
        courseOptions.value = (res.data || []).map((item) => ({
          label: item.name,
          value: item.courseId
        }))
        businessData.value.intentionCourse = ''
      } catch (error) {
        courseOptions.value = []
        console.error('获取课程失败:', error)
      }
    } else {
      courseOptions.value = []
      businessData.value.intentionCourse = ''
    }
  }
)

const getCourseOptions = async () => {
  try {
    const res = await request('system/dict/data/type/course_list')
    courseOptions.value = res.data.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

const statusOptions = ref([])
const focusOptions = ref([])

// 获取跟进状态选项
const getStatusOptions = async () => {
  try {
    const res = await request('system/dict/data/type/business_status')
    statusOptions.value = res.data.map((item) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))

    // 如果后端返回的是label，做一次映射
    const statusItem = statusOptions.value.find(opt => 
      opt.label === businessData.value.status || opt.value === businessData.value.status
    )
    if (statusItem) {
      businessData.value.status = statusItem.value
    }
  } catch (e) {
    statusOptions.value = []
  }
}

// 获取沟通重点
const getFocusOptions = async () => {
  try {
    const res = await request('system/dict/data/type/business_focus')
    focusOptions.value = res.data.map((item) => ({
      label: item.dictLabel,
      value: item.dictValue
    }))
  } catch (e) {
    focusOptions.value = []
  }
}

const goBack = () => {
  router.go(-1)
}

const saveData = () => {
  // 判断沟通重点与沟通纪要是否为空
  if (!businessData.value.focus || !businessData.value.record2) {
    ElMessage.error('跟踪记录不能为空');
    return;
  } else {
    // 拼接 info 数据
    const formattedInfo = `【${businessData.value.focus}】${businessData.value.record2}`;
    businessData.value.info = formattedInfo; // 更新 info

    console.log(businessData.value);

    // 提交数据
    request.post('tienchin/business/follow', businessData.value).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('保存成功');
        goBack()
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

const convertToCustomer = () => {
  // 处理转为成交客户逻辑
}
</script>

<style lang="scss" scoped>
.custom-row {
  margin-top: 8px
}

.left-panel {
  background: #fff;
  padding: 8px;
  border-radius: 6px;
  min-height: 400px;
}
</style>